package com.bio.jsf;

import com.bio.jpa.entities.Feature;
import com.bio.jpa.entities.FeatureKey;
import com.bio.jpa.entities.GenBank;
import com.bio.jpa.entities.Qualifier;
import com.bio.jpa.entities.Status;
import com.bio.jsf.util.JsfUtil;
import com.bio.jpa.session.GenBankFacade;

import java.io.Serializable;
import java.util.*;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean(name = "genBankController")
@SessionScoped
public class GenBankController implements Serializable {

    private GenBank current;
    private Qualifier qual;
    private FeatureKey current_fk;
    private Feature current_feat;
    private List<GenBank> items;
    private boolean show_detail = false;
    private List<Qualifier> tmp_qual = new ArrayList();
    @EJB
    private com.bio.jpa.session.GenBankFacade ejbFacade;
    private PieChartModel pieModel = new PieChartModel();
    private Status tmp_sts;

    public Qualifier getQual() {
        if (qual == null) {
            qual = new Qualifier();
        }
        return qual;
    }

    public void setQual(Qualifier qual) {
        this.qual = qual;
    }

    public PieChartModel getPieModel() {
        pieModel = new PieChartModel();
        int counter = 0;
        HashMap<String, Integer> map = new HashMap<String, Integer>();

        for (FeatureKey fk : getCurrent_feat().getFeatureKeyList()) {
            if (map.containsKey(fk.getStatusStsId().getStsStatus())) {
                counter = map.get(fk.getStatusStsId().getStsStatus()) + 1;
                map.put(fk.getStatusStsId().getStsStatus(), counter);
            } else {
                map.put(fk.getStatusStsId().getStsStatus(), 1);
            }

        }
        for (Iterator it = map.keySet().iterator(); it.hasNext();) {
            Object object = it.next();
            if (object != null) {
                pieModel.set(object.toString(), map.get(object));
            }
        }
        return pieModel;
    }

    public void addQualifier() {
        if (qual.getName() == null || qual.getValue() == null || qual.getName().equalsIgnoreCase("") || qual.getValue().equalsIgnoreCase("")) {
            return;
        }
        if (qual != null) {
            if (!qual.getName().contains("/")) {
                qual.setName("/" + qual.getName());
            }
            qual.setKeyFk(current_fk);
            qual.setSeq(current_fk.getQualifierList().size());
            tmp_qual.add(qual);
            current_fk.getQualifierList().add(qual);
            qual = null;
        }
    }

    public void cancelEditing() {
        current_fk.setStatusStsId(tmp_sts);
        current_fk.getQualifierList().removeAll(tmp_qual);
        tmp_qual.clear();
        qual = null;
    }

    public boolean isShow_detail() {
        return show_detail;
    }

    public void setShow_detail(boolean show_detail) {
        this.show_detail = show_detail;
    }

    public FeatureKey getCurrent_fk() {
        if (current_fk == null) {
            current_fk = new FeatureKey();
        }
        return current_fk;
    }

    public Feature getCurrent_feat() {
        if (current_feat == null) {
            current_feat = new Feature();
        }
        return current_feat;
    }

    public GenBank getGB(int id) {
        return getFacade().find(id);
    }

    public void onProfileSelect(SelectEvent event) {
        Feature tmp = (Feature) event.getObject();
        if (tmp.getName().equalsIgnoreCase("FEATURES")) {
            current_feat = tmp;
        }
    }

    public void onRowSelect(SelectEvent event) {
        tmp_sts = current_fk.getStatusStsId();
        if (!tmp_qual.isEmpty()) {
            cancelEditing();
        }
    }

    public void loadFeatures() {
        for (Feature f : current.getFeatureList()) {
            if (f.getName().equalsIgnoreCase("FEATURES")) {
                current_feat = f;
                show_detail = true;
            }
        }
    }

    public void setCurrent_feat(Feature current_feat) {
        this.current_feat = current_feat;
    }

    public void setCurrent_fk(FeatureKey current_fk) {
        this.current_fk = current_fk;
    }

    public GenBankController() {
    }

    public GenBank getCurrent() {
        if (current != null) {
            for (Feature f : current.getFeatureList()) {
                if (f.getName().equalsIgnoreCase("FEATURES")) {
                    current_feat = f;
                }
            }
        }
        return current;
    }

    public void setCurrent(GenBank current) {
        this.current = current;
    }

    public List<GenBank> getItems() {
        items = getFacade().findAll();
        return items;
    }

    public void setItems(List<GenBank> items) {
        this.items = items;
    }

    private GenBankFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        show_detail = false;
        return "View";
    }

    public String prepareCreate() {
        current = new GenBank();
        return "Create";
    }

    public void flip() {
        show_detail = !show_detail;
    }

    public String create() {
        try {
            current.setCreationDate(new Date());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("GenBankCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("GenBankUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        performDestroy();
        recreateModel();
        return "List";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("GenBankDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void recreateModel() {
        items = null;
    }

    @FacesConverter(forClass = GenBank.class)
    public static class GenBankControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            GenBankController controller = (GenBankController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "genBankController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof GenBank) {
                GenBank o = (GenBank) object;
                return getStringKey(o.getIdGen());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + GenBankController.class.getName());
            }
        }
    }
}
